package com.heart.common.utils;

import com.heart.common.constant.AppConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.security.provider.MD5;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Utils {
    private static Logger logger = LoggerFactory.getLogger(Md5Utils.class);

    public static String md5(String data) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance(AppConstant.MD5);
        } catch (NoSuchAlgorithmException e) {
            logger.error("不支持的加密类型",e);
        }
        char[] charArray = data.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++){
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().toLowerCase();
    }
}
